<template>
  <!-- 已废弃 -->
    <div class="app-container">
      <el-card class="operate-container" shadow="never">
        <i class="el-icon-tickets"></i>
        <span>数据列表</span>
        <span style="margin-left: 20px">{{
          list1.length
            ? formatDate(new Date(list1[0].day * 1000), "yyyy/MM/dd")
            : formatDate(new Date(), "yyyy/MM/dd")
        }}</span>
        <span style="margin-left: 20px; font-size: 14px; color: #409eff">{{
          fileName
        }}</span>
  
        <el-button
          size="mini"
          class="btn-add"
          @click="clearFilter"
          style="margin-left: 20px"
          >清除所有过滤</el-button
        >
      </el-card>
      <div class="table-container">
        <!-- 客户列表 -->
        <el-table
          ref="clientTable"
          :data="list1"
          style="width: 46%; margin-right: 10px"
          v-loading="celientListLoading"
          :default-sort="{ prop: 'date', order: 'descending' }"
          border
        >
          <el-table-column label="客户列表" align="center">
            <el-table-column label="编号" width="65" align="center">
              <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column label="公司名称" width="150" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.companyName }}</p>
              </template>
            </el-table-column>
            <el-table-column
              label="时间"
              align="center"
              prop="time"
              sortable
              :filters="[
                { text: '上午', value: 'AM' },
                { text: '下午', value: 'PM' },
              ]"
              :filter-method="filterMethod"
              width="100"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.time }}</p>
              </template>
            </el-table-column>
            <el-table-column
              label="类型"
              align="center"
              prop="type"
              :filters="[
                { text: '前道', value: 0 },
                { text: '后道', value: 1 },
              ]"
              :filter-method="postFilter"
              width="100"
            >
              <template slot-scope="scope">
                <p>{{ postList[scope.row.type] }}</p>
              </template>
            </el-table-column>
  
            <el-table-column label="地址" align="left">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <el-tag
                    type="danger"
                    style="margin-left: 5px; margin-right: 10px"
                    v-if="scope.row.adressStatus === 1"
                    >错误</el-tag
                  >
                  <div>{{ scope.row.companyAddress }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="指派人员" width="100" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.assignPersonnelName }}</p>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
  
        <!-- 员工列表 -->
        <el-table
          ref="staffTable"
          :data="list2"
          style="width: 46%; margin-left: 10px"
          @selection-change="handleSelectionChange"
          v-loading="staffListLoading"
          border
          show-overflow-tooltip
        >
          <el-table-column label="员工列表" align="center">
            <el-table-column
              type="selection"
              width="60"
              align="center"
              fixed
            ></el-table-column>
            <el-table-column label="编号" width="65" align="center">
              <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column label="姓名" align="center">
              <template slot-scope="scope">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <el-tag
                    type="warning"
                    style="margin-left: 5px; margin-right: 10px"
                    :style="{
                      visibility:
                        scope.row.newPeople === 1 ? 'visible' : 'hidden',
                    }"
                    >新人</el-tag
                  >
                  <div>{{ scope.row.staffName }}</div>
                  <div></div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="地区"
              align="center"
              :filters="areasFilter"
              :filter-method="areasFilters"
              prop="areaId"
            >
              <template slot-scope="scope">
                <p>{{ areaComputed(scope.row.areaId) }}</p>
              </template>
            </el-table-column>
            <el-table-column
              label="职责"
              align="center"
              prop="post"
              :filters="[
                { text: '前道', value: 0 },
                { text: '后道', value: 1 },
              ]"
              :filter-method="postFilter1"
            >
              <template slot-scope="scope">
                <p>{{ postList[scope.row.post] }}</p>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
  
      <div class="btn-container">
        <el-button type="primary" class="btn" @click.stop="getGenreateResult"
          >生成结果</el-button
        >
      </div>
    </div>
  </template>
  <script>
  import {
    updateDeleteStatus,
    updateNewStatus,
    updateRecommendStatus,
    updateHot,
  } from "../../../api/product";
  
  import { FormatCreateTime } from "../../../filter/time";
  
  import {
    OPERATION_STATUS_ARRAY,
    PUBLISH_STATUS_OPTIONS,
  } from "../../../contanst/data";
  import { list, listBySearch, mint, updateStatus } from "../../../api/cert";
  import { Storage } from "../../../store/storage";
  import { handleCurrentChange, handleSizeChange } from "../../../page/page";
  import { DefaultListQuery } from "../../../entity/market";
  import { handleSelectionChange } from "../../../checkbox/handler";
  import { Message } from "element-ui";
  import { formatDate } from "@/utils/date";
  
  import { clientList } from "../../../api/dispatch";
  import { staffList, getArea } from "../../../api/staff";
  const postList = ["前道", "后道"];
  import { mapState } from "vuex";
  
  export default {
    name: "productList",
    data() {
      return {
        postList,
        fileName: "",
        formatDate,
        editSkuInfo: {
          dialogVisible: false,
          productId: null,
          productSn: "",
          productAttributeCategoryId: null,
          stockList: [],
          productAttr: [],
          keyword: null,
        },
        operates: OPERATION_STATUS_ARRAY,
        operateType: null,
        listQuery: Object.assign({}, DefaultListQuery),
        list: [],
        nftTypeId: 0,
        searchTreeProps: {},
        total: 0,
        size: 15,
        currentNftType: "",
        listLoading: true,
        dialogVisible: false,
        selectProductCateValue: null,
        multipleSelection: [],
        productCateOptions: [],
        brandOptions: [],
        publishStatusOptions: PUBLISH_STATUS_OPTIONS,
        list1: [],
        list2: [],
        clientParams: {
          pageNum: 1,
          total: 0,
          pageSize: null,
        },
        staffParams: {
          pageNum: 1,
          total: 0,
          pageSize: null,
        },
        celientListLoading: false,
        staffListLoading: false,
      };
    },
  
    components: {},
  
    created() {
      const { fileName } = this.$route.query;
      if (fileName) {
        this.fileName = fileName;
      }
      this.getAreas();
      this.getList();
    },
  
    computed: {
      ...mapState(["areas"]),
      areaComputed() {
        return (value) => {
          if (this.$store.state.areas) {
            const item = this.$store.state.areas.find(
              (item) => item.id === value
            );
            return item ? item.name : "";
          }
          return this.$store.state.areas;
        };
      },
  
      areasFilter() {
        let data = [];
        let obj = {};
        this.areas.length &&
          this.areas.forEach((item) => {
            obj = {
              text: item.name,
              value: item.id,
            };
            data.push(obj);
          });
  
        return data;
      },
    },
    watch: {
      selectProductCateValue: function (newValue) {
        if (newValue != null && newValue.length == 2) {
          this.listQuery.productCategoryId = newValue[1];
        } else {
          this.listQuery.productCategoryId = null;
        }
      },
      dialogVisible(val) {
        this.dialogVisible = val;
      },
    },
  
    methods: {
      // batchOnChange(value) {
  
      //   console.log("value", value);
  
      // },
      // 地区信息
      getAreas() {
        getArea({
          id: 0,
        }).then((response) => {
          if (response.data && response.data.length) {
            this.$store.commit("SET_AREAS", response.data);
          }
        });
      },
  
      postFilter1(value, row) {
        return row.post === value;
      },
      areasFilters(value, row) {
        return row.areaId === value;
      },
      clearFilter() {
        this.$refs.clientTable.clearFilter();
        this.$refs.staffTable.clearFilter();
      },
  
      postFilter(value, row) {
        return row.type === value;
      },
  
      filterMethod(value, row) {
        let t = row.time.split(":")[0] < 12 ? "AM" : "PM";
        return t === value;
      },
      filterHandler(value, row) {
        return row.userName === value;
      },
  
      handleCurrentChange,
      handleSelectionChange,
      handleSizeChange,
  
      handleMint(index, row) {
        mint({ id: [row.id] }).then((res) => {
          Message({
            message: res.data.message,
            duration: 3 * 1000,
          });
  
          this.list[index].mintStatus = 1;
        });
      },
  
      closeDialog(value) {
        console.log("value", value);
  
        this.$set(this, "dialogVisible", value);
      },
      /**
       * 树形菜单选择
       */
      currentChangeHandle(data) {
        this.currentNftType = data.label;
        this.nftTypeId = data.value;
        this.listQuery.nftType = data.value;
      },
  
      getProductSkuSp(row, index) {
        let spData = JSON.parse(row.spData);
        if (spData != null && index < spData.length) {
          return spData[index].value;
        } else {
          return null;
        }
      },
  
      getResponse(response) {
        this.listLoading = false;
        this.list = response.data;
        this.list.forEach((item) => {
          item.undertakingTime = FormatCreateTime(item.undertakingTime);
          item.createTime = FormatCreateTime(item.createTime);
        });
  
        this.total = response.total;
        this.size = response.pageSize;
        Storage.marketnftByStorage(this.list);
      },
  
      async getList() {
        this.celientListLoading = true;
        this.staffListLoading = true;
        await this.getClientList();
        await this.getStaffList();
      },
  
      getClientList() {
        return clientList({ pageNum: this.clientParams.pageNum }).then((res) => {
          if (this.clientParams.pageNum === 1) {
            this.list1 = [];
          }
          this.clientParams.pageSize = res.data.pageSize;
          this.clientParams.total = res.data.total;
          this.list1 = this.list1.concat(res.data.data);
          const totalPage = Math.ceil(res.data.total / res.data.pageSize);
          if (this.clientParams.pageNum < totalPage) {
            this.clientParams.pageNum++;
            this.getClientList();
          } else {
            this.celientListLoading = false;
          }
        });
      },
  
      getStaffList() {
       return staffList({ pageNum: this.staffParams.pageNum }).then((res) => {
          if (this.staffParams.pageNum === 1) {
            this.list2 = [];
          }
          this.staffParams.pageSize = res.data.pageSize;
          this.staffParams.total = res.data.total;
          this.list2 = this.list2.concat(res.data.data);
          const totalPage = Math.ceil(res.data.total / res.data.pageSize);
          if (this.staffParams.pageNum < totalPage) {
            this.staffParams.pageNum++;
            this.getStaffList();
          } else {
            setTimeout(()=>{
              this.list2 = this.filterEmployeess(
              this.list2,
              this.list1[0].day * 1000
            );
            },0)
            this.staffListLoading = false;
          }
        });
      },
  
      getBrandList() {
        fetchBrandList({ pageNum: 1, pageSize: 100 }).then((response) => {
          this.brandOptions = [];
          let brandList = response.data.data;
          for (let i = 0; i < brandList.length; i++) {
            this.brandOptions.push({
              label: brandList[i].name,
              value: brandList[i].id,
            });
          }
        });
      },
  
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getListBySearch();
      },
  
      getListBySearch() {
        listBySearch(this.listQuery).then((r) => this.getResponse(r));
      },
      handleAddProduct() {
        this.$router.push({ path: "/certificate/addProduct" });
      },
      handleBatchOperate() {
        if (this.operateType == null) {
          this.$message({
            message: "请选择操作类型",
            type: "warning",
            duration: 1000,
          });
          return;
        }
        if (this.multipleSelection == null || this.multipleSelection.length < 1) {
          this.$message({
            message: "请选择要操作的证书",
            type: "warning",
            duration: 1000,
          });
          return;
        }
        this.$confirm("是否要进行该批量操作?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          let ids = [];
  
          console.log(this.multipleSelection);
          let map = {};
          for (let i = 0; i < this.multipleSelection.length; i++) {
            map[this.multipleSelection[i].id] = this.multipleSelection[i];
            ids.push(this.multipleSelection[i].id);
          }
  
          this.operateType.call(ids).then((res) => {
            for (let i = 0; i < this.list.length; i++) {
              if (map[this.list[i].id]) {
                this.list[i][this.operateType.key] = this.operateType.value;
              }
            }
          });
        });
      },
  
      handlePublishStatusChange(index, row) {
        let ids = [];
        ids.push(row.id);
        this.updatePublishStatus(row.status, ids);
      },
      handleNewStatusChange(index, row) {
        let ids = [];
        ids.push(row.mid);
        updateHot(row.hot, ids);
      },
      handleRecommendStatusChange(index, row) {
        let ids = [];
        ids.push(row.id);
        this.updateRecommendStatus(row.recommandStatus, ids);
      },
      handleResetSearch() {
        this.selectProductCateValue = [];
        this.listQuery = Object.assign({}, this.defaultListQuery);
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleDelete(index, row) {
        this.$confirm("是否要进行删除操作?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          let ids = [];
          ids.push(row.id);
          this.updateDeleteStatus(1, ids);
        });
      },
      handleUpdateProduct(index, row) {
        this.$router.push({
          path: "/certificate/updateProduct",
          query: { id: row.id },
        });
      },
      handleShowProduct(index, row) {
        this.dialogVisible = true;
        console.log(row);
        this.$refs.listByProductDetails.pullData(row.mid);
      },
      handleShowVerifyDetail(index, row) {
        console.log("handleShowVerifyDetail", row);
      },
      handleShowLog(index, row) {
        console.log("handleShowLog", row);
      },
      updatePublishStatus(publishStatus, ids) {
        let params = {
          ids: ids,
          status: publishStatus,
        };
        updateStatus(params).then((response) => {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1000,
          });
        });
      },
      updateNewStatus(newStatus, ids) {
        let params = new URLSearchParams();
        params.append("ids", ids);
        params.append("newStatus", newStatus);
        updateNewStatus(params).then((response) => {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1000,
          });
        });
      },
      updateRecommendStatus(recommendStatus, ids) {
        let params = new URLSearchParams();
        params.append("ids", ids);
        params.append("recommendStatus", recommendStatus);
        updateRecommendStatus(params).then((response) => {
          this.$message({
            message: "修改成功",
            type: "success",
            duration: 1000,
          });
        });
      },
      updateDeleteStatus(deleteStatus, ids) {
        let params = new URLSearchParams();
        params.append("ids", ids);
        params.append("deleteStatus", deleteStatus);
        updateDeleteStatus(params).then((response) => {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000,
          });
        });
        this.getList();
      },
      // 过滤派单人员
      filterEmployeess(employee, date = new Date().getTime()) {
        if (!employee.length) return "";
        const dayStart = new Date(date);
        const dayEnd = new Date(date);
        dayStart.setHours(9, 0, 0, 0);
        dayEnd.setHours(18, 0, 0, 0);
  
        return employee.filter((item) => {
          // 保留包含明天时间段或明天上午/下午的员工
          if (item.depart === 0) return false;
          
          if(this.list1.some(i => i.assignPersonnel === item.id))
          return false;
          
          if (
            item.leaveEnd*1000 <= dayStart ||
            (item.leaveStart*1000 <= dayStart && item.leaveEnd*1000 < dayEnd) ||
            (item.leaveStart*1000 >= dayStart && item.leaveEnd*1000 < dayEnd) ||
            item.leaveStart*1000 > dayEnd ||
            (item.leaveEnd === 0 && item.leaveStart === 0) ||
            (item.leaveEnd === null && item.leaveStart === null)
          )
            return true;
  
          // 其他情况过滤掉
          return false;
        });
      },
  
      getGenreateResult() {
        console.log(this.multipleSelection);
        let params = {
          ids: [],
        };
        this.multipleSelection.length &&
          this.multipleSelection.forEach((item) => {
            params.ids.push(item.id);
          });
        if (
          !params.ids.length ||
          params.ids.length < this.list1.length ||
          !this.list1.length
        ) {
          Message.error("数据异常,匹配失败");
          return;
        }
  
        this.$router.push({
          path: "/dispatch/audit",
          query: {
            ids: params.ids
          },
        });
      },
    },
  };
  </script>
  <style>
  .table-container {
    display: flex;
    justify-content: space-between;
    flex: auto;
  }
  .el-table {
    height: max-content !important;
  }
  .btn-container {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    margin-top: 25px;
  }
  .btn {
    width: 260px;
    height: 40px;
    font-size: 16px;
    letter-spacing: 2px;
  }
  </style>
  
  
  